package com.cch.datageniebackendmaster.controller;

import cn.hutool.json.JSONUtil;
import com.cch.datageniebackendmaster.config.TrackedTask;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程测试
 *
 * @author cch
 */
@Slf4j
@Api(tags = "线程测试")
@RestController
@RequestMapping("queue")
public class QueueController {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("add")
    public void add(String name) {
        TrackedTask trackedTask = new TrackedTask(() -> {
            log.info("任务执行中，" + name + "，执行人：" + Thread.currentThread().getName());
            try {
                Thread.sleep(600000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, 1L);
        threadPoolExecutor.execute(trackedTask);
    }

    @GetMapping("get")
    public String get() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("当前线程数", threadPoolExecutor.getPoolSize());
        map.put("正在工作线程数", threadPoolExecutor.getActiveCount());
        map.put("队列大小", threadPoolExecutor.getQueue().size());
        map.put("任务总数", threadPoolExecutor.getTaskCount());
        map.put("任务完成数", threadPoolExecutor.getCompletedTaskCount());
        return JSONUtil.toJsonStr(map);
    }

}
